package com.example.cameraalbumtest;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.icu.text.UFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.annotation.Target;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    public static final int TAKE_PHOTO = 1;

    public static final int CHOOSE_PHOTO = 2;

    private ImageView picture;

    private Uri imageUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 开启相机获取图片
        findViewById(R.id.take_photo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 1.创建File对象,用于储存拍照后的照片
                File file = getFile();
                // 2.获取图片的uri
                getUri(file);
                //开启相机
                takePhoto();
            }
        });

        // 打开相册选取图片
        findViewById(R.id.choose_from_photo).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 1.获取权限
                    if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                    } else {
                        //2.打开相册
                        openAlbum();
                    }
                }
        });
    }

    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        //3.获取结果
        startActivityForResult(intent, CHOOSE_PHOTO);
    }

    private void getUri(File file) {
        // 2.sdk 兼容性编码
        if (Build.VERSION.SDK_INT >= 24) {
            // 如果大于24(7.0),直接获取uri
            imageUri = FileProvider.getUriForFile(MainActivity.this, "com.example.cameraalbumtest.fileprovider", file);
        } else {
            // 如果小于24(7.0),将对象转换成uri对象
            imageUri = Uri.fromFile(file);
        }
    }

    private void takePhoto() {
        // 3.启动相机
//                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        //ActivityCompat.requestPermissions(context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        //ActivityCompat.requestPermissions(context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, TAKE_PHOTO);
    }

    @NonNull
    private File getFile() {
        File file = new File(getExternalCacheDir(), "output_image.jpg"); // getExternalCacheDir()获取当前应用缓存数据的path
        try {
            if (file.exists()) {
                file.delete();
            }
            boolean createNewFile = file.createNewFile();
            Log.i(TAG, "onClick: createNewFile=" + createNewFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PHOTO:
                Log.i(TAG, "onActivityResult: TAKE_PHOTO RESULT_OK=" + RESULT_OK);
                if (requestCode == RESULT_OK) {
                    try {
                        // 将拍摄的照片显示出来
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        picture.setImageBitmap(bitmap);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case CHOOSE_PHOTO:
                Log.i(TAG, "onActivityResult: CHOOSE_PHOTO RESULT_OK=" + RESULT_OK);
                if (requestCode == RESULT_OK) {
                    if (Build.VERSION.SDK_INT >= 19) {
                        // 4.4及以上版本用这个方法处理图片,这是因为4.4,选中图片不再返回真实的uri,而是一个封装过的uri,因此我们需要进行解析.
                        handleImageOkKitKat(data); // 解析uri
                        // 4.4以下用这个方法
                        handleImageBeforeKitKat(data);
                    }
                }
                break;
            default:
                Log.i(TAG, "onActivityResult: default");
                break;
        }
    }

    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }

    @TargetApi(19)
    private void handleImageOkKitKat(Intent data) {
        // 解析1: 如果 uri 是 document 类型的,那就取出 document id 进行解析,如果不是的话,就进行普通的处理
        // 解析2: 另外,如果 Uri 的 authority 部分是 media 格式的话, document id 还需要进一步解析,然后通过字符串分割的方式取出后半部分才能得到真正的数字id
        // 解析3: 取出的 id 用于构建新的 Uri 和查询语句,然后把这些值作为参数传入 getImagePath() 方法中
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果 document 类型的 uri, 则通过document id 处理
            String documentId = DocumentsContract.getDocumentId(uri);

            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = documentId.split(":")[0]; // 解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);

            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public/public_downloads"), Long.valueOf(documentId));
                imagePath = getImagePath(contentUri, null);
            } else if ("content".equalsIgnoreCase(uri.getScheme())) {
                // 如果是 content 类型的 Uri ,使用普通方式获取 uri
                imagePath = getImagePath(uri, null);
            } else if ("file".equalsIgnoreCase(uri.getScheme())) {
                // 如果是 file 类型的 Uri ,直接获取图片路径即可
                imagePath = uri.getPath();
            }
            displayImage(imagePath); // 根据图片路径显示图片
        }
    }

    private void displayImage(String imagePath) {
        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            picture.setImageBitmap(bitmap);
        } else {
            Toast.makeText(MainActivity.this, "failed to get image.", Toast.LENGTH_SHORT).show();
        }
    }

    @SuppressLint("Range")
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过 Uri 和 selection 来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToNext()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openAlbum();
                } else {
                    Toast.makeText(MainActivity.this, "You denied the permission.", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                Log.i(TAG, "onRequestPermissionsResult: default");
                break;
        }
    }
}